﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Endos.Wodice
{
    public class DicePool
    {
        private readonly static Random random;

        public int Quantity { get; set; }

        public bool OldSystem { get; set; }

        public bool CancellerSuccess { get; set; }

        public Difficulty Difficulty { get; set; }

        public Explosion Explosion { get; set; }

        public int ThrowDice
        {
            get
            {
                return random.Next(1, 11);
            }
        }

        static DicePool()
        {
            random = new Random();
        }

        public IEnumerable<int> Roll(out int? amountSuccess)
        {
            var result = new List<int>();
            amountSuccess = 0;
            var amountDices = Quantity;

            if (!OldSystem && amountDices <= 0)
            {
                amountDices = 0;

                var dice = ThrowDice;

                result.Add(dice);

                if (dice == 10)
                {
                    amountSuccess++;
                    amountDices++;
                }
                else if (dice == 1)
                {
                    amountSuccess = null;
                }
            }

            var noneSucess = true;
            var difficulty = (int)Difficulty;
            var explosion = (int)Explosion;

            while (amountDices > 0)
            {
                var dice = ThrowDice;

                if (dice >= difficulty)
                {
                    amountSuccess++;
                    noneSucess = false;
                }

                if (dice >= explosion)
                {
                    amountDices++;
                }
                else if (CancellerSuccess && dice == 1)
                {
                    amountSuccess--;
                }

                result.Add(dice);

                amountDices--;
            }

            if (OldSystem && noneSucess && amountSuccess < 0)
            {
                amountSuccess = null;
            }

            return result.OrderByDescending(e => e);
        }
    }
}
